package com.jeeplus.modules.guide.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.Result;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.config.web.Servlets;
import com.jeeplus.modules.guide.entity.*;
import com.jeeplus.modules.guide.service.*;
import com.jeeplus.modules.guide.utils.ImgUtils;
import com.jeeplus.modules.guide.utils.JsonObjectUtils;
import com.jeeplus.modules.guide.utils.MatterUtils;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.work.queue.entity.ElectronicMaterialEntity;
import com.jeeplus.modules.work.queue.service.ElectronicMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;
import org.im4java.process.ProcessStarter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags="一码办成事事项功能")
@RestController
@RequestMapping("/ymbcsMatter")
@RequiredArgsConstructor
public class YmbcsMatterController {
    private static final Logger log = LoggerFactory.getLogger(YmbcsMatterController.class);
    private final YmbcsMatterService ymbcsMatterService;
    private final MatterUtils matterUtils;
    private final VersionService versionService;
    private final MobileQueueService mobileQueueService;
    private final MobileIndexService mobileIndexService;
    private final ElectronicMaterialService electronicMaterialService;
    private final MobileMatterService mobileMatterService;

    /**
     * 一码办成事事项分类展示
     *
     * @return
     */
    @ApiOperation(value = "一码办成事事项分类展示")
    @GetMapping(value ="ymbcsMatterList")
    public Result<List<YmbcsLabel>> ymbcsMatterList(String searchWords){
        List<YmbcsLabel> maps = ymbcsMatterService.ymbcsMatterType();
        List<YmbcsMatter> list = ymbcsMatterService.ymbcsMatterList(searchWords,versionService.getVersion());
        for(YmbcsLabel map : maps){
            if(map.getList() == null)map.setList(new ArrayList<YmbcsMatter>());
            for(YmbcsMatter ym : list){
                if(map.getLabelValue().equals(ym.getOrganType())){
                    map.getList().add(ym);
                }
            }
        }
        return Result.succeed(maps,"操作成功！");
    }

    /**
     * 一码办成事网办事项展示
     *
     * @return
     */
    @ApiOperation(value = "一码办成事网办事项展示")
    @GetMapping(value ="ymbcsMatterOnline")
    public Result<List<YmbcsLabel>> ymbcsMatterOnline(String searchWords){
        List<YmbcsLabel> maps = new ArrayList<YmbcsLabel>();
        YmbcsLabel yl = new YmbcsLabel();
        yl.setList(ymbcsMatterService.ymbcsMatterListOnline(searchWords,versionService.getVersion()));
        yl.setLabelValue("all");
        yl.setLabel("网办事项");
        maps.add(yl);
        return Result.succeed(maps,"操作成功！");
    }

    /**
     * 一码办成事网办事项信息
     *
     * @return
     */
    @ApiOperation(value = "一码办成事网办事项信息")
    @GetMapping(value ="ymbcsMatterOnlineByName")
    public AjaxJson ymbcsMatterOnlineByName(String matterName){
        List<String> strings = ymbcsMatterService.ymbcsMatterListOnlineByName(versionService.getVersion(), matterName);
        String ids = "";
        for(String s : strings){
            ids+=s+",";
        }
        return AjaxJson.success("操作成功").put("data",ids);
    }
    /**
     * 一码办成事事项情形化展示
     *
     * @return
     */
    @ApiOperation(value = "一码办成事事项情形化展示")
    @GetMapping(value = "ymbcsSituationList")
    public AjaxJson ymbcsSituationList(String oid){
        return AjaxJson.success().put("data",matterUtils.findSisutionValue(oid));
    }

    /**
     * 一码办成事事项办事指南展示
     *
     * @return
     */
    @ApiOperation(value = "一码办成事事项办事指南展示")
    @GetMapping(value = "ymbcsBsznList")
    public AjaxJson ymbcsBsznList(String oid,String ids,String organType){
        List<MobileMaterial> list = null;
        List<String> valuesStr = new ArrayList<String>();
        Map<String,Object> values = mobileIndexService.getMatterBSZN(oid,versionService.getVersion(),"0");
        int valueSize = 0;
        if(null != values){
            List<Map<String,String>> map = mobileQueueService.getCloseValue();
            JSONArray json = null;
            if("street".equals(organType)){
                values.put("organName","街道办事处");
                json = new JSONArray();
                List<YmbcsMatterBszn> listValue = ymbcsMatterService.ymbcsStreeList(mobileIndexService.getMatterName(versionService.getVersion(),oid),versionService.getVersion());
                valueSize = listValue.size();
                if(valueSize >= 2)json.add("各街道综合便民服务中心");
                for(int i =0;i<valueSize;i++){
                    if(valueSize >= 2){
                        valuesStr.add((i+1)+"、"+listValue.get(i).getOrganName()+":"+listValue.get(i).getZxDhText());
                    } else{
                        valuesStr.add(listValue.get(i).getOrganName()+":"+listValue.get(i).getZxDhText());
                        json.addAll(JSONArray.parseArray(listValue.get(i).getLocationAddr()));
                    }

                }
                values.put("telList",valuesStr);
            }else{
                json = JSONArray.parseArray(values.get("locationAddr").toString());
                valuesStr.add(values.get("zxDhText")+"");
                values.put("telList",valuesStr);
            }
            valueSize = json.size();
            if(!map.isEmpty()){
                String address = "";
                for(Map<String,String> m : map){
                    if(null != m.get("address")){
                        address += m.get("address")+"-";
                    }
                }
                for(int i =0;i< valueSize;i++){
                    if(address.contains(json.getString(i))){
                        json.remove(i);
                    }
                }
                if(json.size() == 0){
                    json.add("该办理地址临时关闭！");
                }
            }
            if(valueSize >= 2){
                String jsonValues = "";
                for(int k =0;k< valueSize;k++){
                    jsonValues = json.getString(k);
                    json.remove(k);
                    json.add(k,(k+1)+"、"+jsonValues);
                }
            }
            values.put("locationAddr",json);
        }

        if(StringUtils.isNotBlank(ids)){
            try{
                JSONObject js = matterUtils.getMaterialValue(ids);
                if("200".equals(js.getString("code")) && StringUtils.isNotBlank(js.getString("data"))){
                    list = JSONArray.parseArray(js.getString("data"), MobileMaterial.class);
                    for(MobileMaterial mm : list){
                        if(StringUtils.isBlank(mm.getMaterialName())){
                            mm.setMaterialName(mm.getRawMaterialName());
                        }
                        mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
                    }
                }
                return AjaxJson.success("事项办事指南加载成功！").put("matter", values).put("data",list);
            }catch(Exception e){
                log.error(e.getMessage());
                log.error("获取事项办事指南失败！oid:"+oid);
                return AjaxJson.error("获取事项办事指南失败！");
            }
        }else{
            try{
                String result = mobileIndexService.getMatterMaterialList(oid,versionService.getVersion());
                if(StringUtils.isNotBlank(result)){
                    list = JSONArray.parseArray(result, MobileMaterial.class);
                    for(MobileMaterial mm : list){
                        if(StringUtils.isBlank(mm.getMaterialName())){
                            mm.setMaterialName(mm.getRawMaterialName());
                        }
                        mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
                    }
                }
                return AjaxJson.success("事项办事指南加载成功！").put("matter", values).put("data",list);
            }catch(Exception e){
                log.error(e.getMessage());
                e.printStackTrace();
                log.error("获取事项办事指南失败！oid:"+oid);
                return AjaxJson.error("获取办事指南失败！");
            }
        }
    }


    /**
     * 一码办成事事项办事指南展示
     *
     * @return
     */
    @ApiOperation(value = "一码办成事事项办事指南展示")
    @GetMapping(value ="ymbcsBsznListCheckUser")
    public AjaxJson ymbcsBsznListCheckUser(String oid,String ids,String otherVersion) {
        List<MobileMaterial> list = null;
        List<Map<String, Object>> maps = ymbcsMatterService.ymbcsMyMaterialList(UserUtils.getUser().getLoginName(),oid);
        List<String> idcardList = new ArrayList<String>(2);
        List<String> idcardListRE = new ArrayList<String>(2);
        idcardList.add("undefined");
        idcardList.add("undefined");
        idcardListRE.add("undefined");
        idcardListRE.add("undefined");
        if(StringUtils.isNotBlank(ids)){
            try{
                JSONObject js = matterUtils.getMaterialValue(ids);
                if("200".equals(js.getString("code")) && StringUtils.isNotBlank(js.getString("data"))){
                    list = JSONArray.parseArray(js.getString("data"), MobileMaterial.class);
                    for(MobileMaterial mm : list){
                        if(StringUtils.isBlank(mm.getMaterialName())){
                            mm.setMaterialName(mm.getRawMaterialName());
                        }
                        for(Map<String, Object> map : maps){
                            if(mm.getMaterialName().contains(map.get("name").toString())){
                                mm.getMaterialList().add(map.get("materialsUrl").toString());
                            }else if(mm.getMaterialName().contains("身份证")){
                                if(mm.getMaterialName().contains("法人")){
                                    if(String.valueOf(map.get("name")).contains("身份证") && String.valueOf(map.get("name")).contains("法人")){
                                        if(String.valueOf(map.get("name")).contains("正面")){
                                            idcardListRE.set(0,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }else if(String.valueOf(map.get("name")).contains("反面")){
                                            idcardListRE.set(1,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }

                                    }
                                }else{
                                    if(String.valueOf(map.get("name")).contains("身份证") && !String.valueOf(map.get("name")).contains("法人")){
                                        if(String.valueOf(map.get("name")).contains("正面")){
                                            idcardList.set(0,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }else if(String.valueOf(map.get("name")).contains("反面")){
                                            idcardList.set(1,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }

                                    }
                                }
                            }
                        }
                        if(mm.getMaterialName().contains("身份证")){
                            if(mm.getMaterialName().contains("法人")){
                                mm.getMaterialList().addAll(idcardListRE);
                            }else{
                                mm.getMaterialList().addAll(idcardList);
                            }
                        }
                        mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
                    }
                }
                idcardList.clear();idcardListRE.clear();
                return AjaxJson.success("事项办事指南加载成功！").put("matter", mobileIndexService.getMatterBSZN(oid,versionService.getVersion(),otherVersion)).put("data",list);
            }catch(Exception e){
                log.error(e.getMessage());
                log.error("获取事项办事指南失败！oid:"+oid);
                return AjaxJson.error("获取事项办事指南失败！");
            }
        }else{
            try{
                String result = mobileIndexService.getMatterMaterialList(oid,versionService.getVersion());
                if(StringUtils.isNotBlank(result)){
                    list = JSONArray.parseArray(result, MobileMaterial.class);
                    for(MobileMaterial mm : list){
                        if(StringUtils.isBlank(mm.getMaterialName())){
                            mm.setMaterialName(mm.getRawMaterialName());
                        }
                        for(Map<String, Object> map : maps){
                            if(mm.getMaterialName().contains(map.get("name").toString())){
                                mm.getMaterialList().add(map.get("materialsUrl").toString());
                            }else if(mm.getMaterialName().contains("身份证")){
                                if(mm.getMaterialName().contains("法人")){
                                    if(String.valueOf(map.get("name")).contains("身份证") && String.valueOf(map.get("name")).contains("法人")){
                                        if(String.valueOf(map.get("name")).contains("正面")){
                                            idcardListRE.set(0,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }else if(String.valueOf(map.get("name")).contains("反面")){
                                            idcardListRE.set(1,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }

                                    }
                                }else{
                                    if(String.valueOf(map.get("name")).contains("身份证") && !String.valueOf(map.get("name")).contains("法人")){
                                        if(String.valueOf(map.get("name")).contains("正面")){
                                            idcardList.set(0,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }else if(String.valueOf(map.get("name")).contains("反面")){
                                            idcardList.set(1,map.get("materialsUrl").toString().replace("/api","/gxsys"));
                                        }

                                    }
                                }
                            }
                        }
                        if(mm.getMaterialName().contains("身份证")){
                            if(mm.getMaterialName().contains("法人")){
                                mm.getMaterialList().addAll(idcardListRE);
                            }else{
                                mm.getMaterialList().addAll(idcardList);
                            }
                        }
                        mm.setMaterialName(mm.getMaterialName()+"("+mm.getRawSource()+"/"+mm.getRawPaperNumber()+"份/"+mm.getRawMaterialType()+")");
                    }
                }
                idcardList.clear();idcardListRE.clear();
                return AjaxJson.success("事项办事指南加载成功！").put("matter", mobileIndexService.getMatterBSZN(oid,versionService.getVersion(),otherVersion)).put("data",list);
            }catch(Exception e){
                log.error(e.getMessage());
                log.error("获取事项办事指南失败！oid:"+oid);
                return AjaxJson.error("获取办事指南失败！");
            }
        }
    }



    /**
     * 获取我的电子材料
     *
     * @return
     */
    @GetMapping(value = "ymbcsMaterialList")
    public AjaxJson ymbcsMaterialList(String idcard){
        List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(1);
        map.add(new HashMap<String,Object>());
        map.get(0).put("id","123456789");
        map.get(0).put("name","我的电子材料清单");
        Boolean flag = false;
        List<Map<String, Object>> removeListPerson = new ArrayList<Map<String, Object>>();
        Boolean flagFR = false;
        List<Map<String, Object>> removeListFR = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> maps = ymbcsMatterService.ymbcsMaterialList(idcard);
        for(int k =0;k<maps.size();k++){
            maps.get(k).put("children",new ArrayList<>());
            if(!maps.get(k).get("name").toString().contains("法人") && maps.get(k).get("name").toString().contains("身份证") && (maps.get(k).get("name").toString().contains("正面") || maps.get(k).get("name").toString().contains("反面"))){
                removeListPerson.add(maps.get(k));
            }else if(maps.get(k).get("name").toString().contains("身份证整面")){
                flag = true;
            }
            if(maps.get(k).get("name").toString().contains("法人") && maps.get(k).get("name").toString().contains("身份证") && (maps.get(k).get("name").toString().contains("正面") || maps.get(k).get("name").toString().contains("反面"))){
                removeListFR.add(maps.get(k));
            }else if(maps.get(k).get("name").toString().contains("法人身份证整面")){
                flagFR = true;
            }
        }
        String imga,imgb,imgd;
        if(flag){
            maps.removeAll(removeListPerson);
        }else if(removeListPerson.size() == 2) {
            imga = removeListPerson.get(0).get("materialsUrl").toString();
            imgd = imga;
            imgb = removeListPerson.get(1).get("materialsUrl").toString();
            imga = JeePlusProperites.newInstance().getUserfilesBaseDir()+imga.replace("/api/","");
            imgb = JeePlusProperites.newInstance().getUserfilesBaseDir()+imgb.replace("/api/","");
            String imgc = imga.substring(0,imga.lastIndexOf("/")+1)+"身份证整面.jpg";
            if(ImgUtils.ImgToDo(imga,imgb,imgc)){
                Map<String, Object> m = removeListPerson.get(0);
                ElectronicMaterialEntity entity = new ElectronicMaterialEntity();
                entity.setMaterialsUrl(imgd.substring(0,imgd.lastIndexOf("/")+1)+"身份证整面.jpg");
                entity.setElectronicMaterialsName("身份证整面");
                entity.setMaterialsType("jpg");
                entity.setMaterialsItem("2");
                entity.setCreateTime(DateUtils.getDateTime());
                entity.setStatus("0");
                entity.setMaterialId("无");
                entity.setOid("无");
                entity.setSort("1");
                entity.setLoginId(mobileMatterService.findWXIdByIdcard(idcard));
                m.put("name",entity.getElectronicMaterialsName());
                m.put("materialsUrl",entity.getMaterialsUrl());
                electronicMaterialService.upElectronicMaterial(entity);
                maps.removeAll(removeListPerson);
                maps.add(m);
                removeListPerson.clear();
            }
        }
        if(flagFR){
            maps.removeAll(removeListFR);
        }else if(removeListFR.size() == 2) {
            imga = removeListFR.get(0).get("materialsUrl").toString();
            imgd = imga;
            imgb = removeListFR.get(1).get("materialsUrl").toString();
            imga = JeePlusProperites.newInstance().getUserfilesBaseDir()+imga.replace("/api/","");
            imgb = JeePlusProperites.newInstance().getUserfilesBaseDir()+imgb.replace("/api/","");
            String imgc = imga.substring(0,imga.lastIndexOf("/")+1)+"法人身份证整面.jpg";
            if(ImgUtils.ImgToDo(imga,imgb,imgc)){
                Map<String, Object> m = removeListFR.get(0);
                ElectronicMaterialEntity entity = new ElectronicMaterialEntity();
                entity.setMaterialsUrl(imgd.substring(0,imgd.lastIndexOf("/")+1)+"法人身份证整面.jpg");
                entity.setElectronicMaterialsName("法人身份证整面");
                entity.setMaterialsType("jpg");
                entity.setMaterialsItem("2");
                entity.setCreateTime(DateUtils.getDateTime());
                entity.setStatus("0");
                entity.setMaterialId("无");
                entity.setOid("无");
                entity.setSort("1");
                entity.setLoginId(mobileMatterService.findWXIdByIdcard(idcard));
                m.put("name",entity.getElectronicMaterialsName());
                m.put("materialsUrl",entity.getMaterialsUrl());
                electronicMaterialService.upElectronicMaterial(entity);
                maps.removeAll(removeListFR);
                maps.add(m);
                removeListFR.clear();
            }
        }
        map.get(0).put("children",maps);
        return AjaxJson.success().put("treeData",map);
    }

    /**
     * 获取我的电子材料图片
     *
     * @return
     */
    @GetMapping(value = "ymbcsImgList")
    public void ymbcsImgList(String url, HttpServletResponse response) throws IOException {
        String fileUrl = FileKit.getAttachmentUrl();
        url = url.substring(url.lastIndexOf("userfiles"),url.length());
        FileInputStream input=new FileInputStream(new File(fileUrl+url));
        byte[] data = new byte[input.available()];
        input.read(data);
        response.getOutputStream().write(data);
    }

    /**
     * 获取我的电子材料图片
     *
     * @return
     */
    @GetMapping(value = "ymbcsMaterialDo")
    public AjaxJson ymbcsImgList(String oid){
        String url = ymbcsMatterService.ymbcsMaterialDo(oid);
        if(StringUtils.isNotBlank(url)){
            return AjaxJson.success().put("data",url+UserUtils.getUser().getLoginName());
        }else{
            return AjaxJson.error("无外链接").put("code",400);
        }
    }

    /**
     * 获取税务网上办地址
     * matterSWList
     * @return 受影响的行数
     */
    @GetMapping("/matterSWList")
    public AjaxJson matterSWList(String searchWords) {
        User user = UserUtils.getUser();
        if(null == user){
            return AjaxJson.error("用户无效");
        }else{
            List<HashMap<String,String>> map = ymbcsMatterService.matterSWList(searchWords);
            for(HashMap<String,String> m : map){
                m.put("url",m.get("url")+"?id="+user.getId());
            }
            return AjaxJson.success().put("data",map);
        }
    }

    /**
     * 获取材料地址
     * findmaterialsUrl
     * @return 受影响的行数
     */
    @GetMapping("/findmaterialsUrl")
    public AjaxJson findmaterialsUrl(String id) {
        return AjaxJson.success().put("data",ymbcsMatterService.findmaterialsUrl(id));
    }


    @RequestMapping(value = "/findMaterialsListName", method = RequestMethod.GET)
    public void findMaterialsListName(){
        List <HashMap <String, String>> materialsListName = ymbcsMatterService.findMaterialsListName();
        for(HashMap <String, String> m : materialsListName){
            String materialList = m.get("materialList");
            JSONArray jsonArray = JSONArray.parseArray(materialList);
            for(int i=0;i<jsonArray.size();i++){
                ymbcsMatterService.intomateriallist(m.get("oid"),m.get("matterName"),jsonArray.getJSONObject(i).getString("rawMaterialName").trim());
            }
        }

    }


}
